<template>
  <!-- 表格头部 -->
  <div class="header">
    <el-button @click="openAddDia" type="primary"
      >添加用户<el-icon><Plus /></el-icon
    ></el-button>
  </div>

  <!-- 表格数据 -->
  <el-table
    :data="compTableData"
    border
    stripe
    style="min-width: 1200px; max-width: 1200px"
  >
    <el-table-column class="usuususu" label="账号">
      <template v-slot="{ row }">
        <span class="username" @click="handleDetail(row)">{{
          row.username
        }}</span>
      </template>
    </el-table-column>

    <el-table-column prop="nickname" label="昵称" />
    <el-table-column prop="gender" label="性别" />
    <el-table-column prop="age" label="年龄" />
    <el-table-column prop="identity" label="身份" />

    <el-table-column label="操作">
      <template #default="{ row }">
        <el-button @click="openEdit(row)" type="primary" size="small"
          >编辑</el-button
        >
        <el-popconfirm
          width="220"
          confirm-button-text="确定"
          cancel-button-text="取消"
          icon-color="#626AEF"
          title="你确定要删除此项吗？"
          @confirm="handleDelet(row)"
        >
          <template #reference>
            <el-button type="danger" size="small">删除</el-button>
          </template>
        </el-popconfirm>
      </template>
    </el-table-column>
  </el-table>

  <!-- 分页组件 -->
  <el-pagination
    v-model:current-page="currentPage"
    v-model:page-size="pageSize"
    :small="false"
    :disabled="false"
    :background="false"
    layout="total, prev, pager, next, jumper"
    :total="tableData.length"
  />

  <!-- 添加用户对话框 -->
  <el-dialog
    v-model="addDialog"
    :before-close="resetForm"
    title="添加新用户窗口"
    width="40%"
  >
    <el-form ref="addForm" :model="addData" label-width="120px" :rules="rules">
      <el-form-item label="账号" prop="username">
        <el-input v-model="addData.username" />
      </el-form-item>

      <el-form-item label="密码" prop="password">
        <el-input v-model="addData.password" />
      </el-form-item>

      <el-form-item label="昵称" prop="nickname">
        <el-input v-model="addData.nickname" />
      </el-form-item>

      <el-form-item label="性别" prop="gender">
        <el-select v-model="addData.gender" placeholder="请选择性别">
          <el-option label="男" value="男" />
          <el-option label="女" value="女" />
        </el-select>
      </el-form-item>

      <el-form-item label="年龄" prop="age">
        <el-input v-model="addData.age" />
      </el-form-item>

      <el-form-item label="身份" prop="identity">
        <!-- <el-input v-model="addData.identity" /> -->
        <el-select v-model="addData.identity" placeholder="请选择身份">
          <el-option label="会计" value="会计" />
          <el-option label="人事" value="人事" />
          <el-option label="前端开发工程师" value="前端开发工程师" />
          <el-option label="后端开发工程师" value="后端开发工程师" />
          <el-option label="项目经理" value="项目经理" />
          <el-option label="产品经理" value="产品经理" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="resetForm">取消</el-button>
        <el-button type="primary" @click="handleAdd"> 确认 </el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 详情页面 -->
  <el-dialog
    v-model="detailsDialog"
    :title="isEdit ? '用户详情' : '编辑用户'"
    width="40%"
    :before-close="resetForm"
  >
    <el-form
      ref="detailsForm"
      :model="detailsData"
      label-width="120px"
      :rules="rules"
    >
      <el-form-item label="账号" prop="username">
        <el-input :disabled="isEdit" v-model="detailsData.username" />
      </el-form-item>

      <el-form-item label="密码" prop="password">
        <el-input :disabled="isEdit" v-model="detailsData.password" />
      </el-form-item>

      <el-form-item label="昵称" prop="nickname">
        <el-input :disabled="isEdit" v-model="detailsData.nickname" />
      </el-form-item>

      <el-form-item label="性别" prop="gender">
        <el-select
          :disabled="isEdit"
          v-model="detailsData.gender"
          placeholder="请选择性别"
        >
          <el-option label="男" value="男" />
          <el-option label="女" value="女" />
        </el-select>
      </el-form-item>

      <el-form-item label="年龄" prop="age">
        <el-input :disabled="isEdit" v-model="detailsData.age" />
      </el-form-item>

      <el-form-item label="身份" prop="identity">
        <!-- <el-input v-model="detailsData.identity" /> -->
        <el-select
          :disabled="isEdit"
          v-model="detailsData.identity"
          placeholder="请选择身份"
        >
          <el-option label="会计" value="会计" />
          <el-option label="人事" value="人事" />
          <el-option label="前端开发工程师" value="前端开发工程师" />
          <el-option label="后端开发工程师" value="后端开发工程师" />
          <el-option label="项目经理" value="项目经理" />
          <el-option label="产品经理" value="产品经理" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="resetForm">{{
          isEdit === true ? "关闭" : "取消"
        }}</el-button>
        <el-button v-show="!isEdit" type="primary" @click="handleEdit">
          确认
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { mapState } from 'vuex';
import { getList, adduser, edit, deletuser } from '@/api/user';
import { Plus } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
export default {
  data() {
    return {
      // 表格数据
      tableData: [],
      // 当前页
      currentPage: 1,
      // 每页数据数量
      pageSize: 10,
      // 添加用户弹窗是否显示
      addDialog: false,
      // 添加用户页面数据
      addData: {
        username: '',
        password: '',
        nickname: '',
        identity: '',
        gender: '',
        age: '',
      },
      // 添加用户表单验证规则
      rules: {
        username: [
          {
            validator: this.validateUserName,
            required: true,
            trigger: 'blur',
          },
        ],
        password: [
          {
            required: true,
            trigger: 'blur',
            message: '请输入密码！',
          },
        ],
        nickname: [
          {
            validator: this.validateNickname,
            required: true,
            message: '请输入昵称',
            trigger: 'blur',
          },
        ],
        gender: [
          {
            validator: this.validateGender,
            required: true,
            message: '请选择性别',
            trigger: 'blur',
          },
        ],
        age: [
          {
            validator: this.validateAge,
            required: true,
            trigger: 'blur',
          },
        ],
        identity: [
          {
            validator: this.validateIdentity,
            required: true,
            message: '请选择身份',
            trigger: 'blur',
          },
        ],
      },

      // 详情对话框
      detailsDialog: false,
      // 详情页数据
      detailsData: {
        username: '',
        password: '',
        nickname: '',
        identity: '',
        gender: '',
        age: '',
      },
      // 是否编辑
      isEdit: true,
      // 编辑账户的id
      editId: '',
    };
  },
  components: {
    Plus,
  },
  computed: {
    ...mapState(['userInfo']),
    compTableData() {
      return this.tableData.slice(
        (this.currentPage - 1) * this.pageSize,
        (this.currentPage - 1) * this.pageSize + this.pageSize
      );
    },
  },
  methods: {
    // 请求用户列表
    getUsers() {
      getList().then((res) => {
        this.tableData = res;
      });
    },

    // 添加对话框重置
    resetForm() {
      this.isEdit = true;
      this.addDialog = false;
      this.detailsDialog = false;
      this.$refs?.addForm?.resetFields?.();
      this.$refs?.detailsForm?.resetFields?.();
    },

    // 点击添加用户出现弹出框
    openAddDia() {
      this.addDialog = true;
    },

    // 确认添加操作
    handleAdd() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          adduser(this.addData).then(() => {
            this.getUsers();
          });
          this.resetForm();
        } else {
          ElMessage({
            type: 'error',
            message: '请确保输入必要项目！',
          });
        }
      });
    },

    // 验证用户名
    validateUserName(rule, value, callback) {
      const reg = new RegExp('^[A-Za-z0-9\u4e00-\u9fa5]+$');
      if (reg.test(value)) {
        callback();
      } else if (!value) {
        callback(new Error('请输入账号！'));
      } else {
        callback(new Error('账号存在非法字符！'));
      }
    },

    // 验证年龄
    validateAge(rule, value, callback) {
      const val = Number(value);
      if (val > 0 && val < 100 && Number.isInteger(val)) {
        callback();
      } else if (!value) {
        callback(new Error('请输入年龄！'));
      } else {
        callback(new Error('请输入小于100的正整数'));
      }
    },

    // 打开用户详情窗口
    handleDetail(row) {
      this.detailsDialog = true;
      this.detailsData.username = row.username;
      this.detailsData.password = row.password;
      this.detailsData.nickname = row.nickname;
      this.detailsData.identity = row.identity;
      this.detailsData.gender = row.gender;
      this.detailsData.age = row.age;
    },

    // 打开编辑窗口
    openEdit(row) {
      this.handleDetail(row);
      this.isEdit = false;
      this.editId = row.id;
    },

    // 确认编辑
    handleEdit() {
      edit(this.editId, this.detailsData).then(() => {
        this.getUsers();
      });
      this.detailsDialog = false;
      this.isEdit = true;
    },

    // 删除功能
    handleDelet(row) {
      deletuser(row.id).then((res) => {
        console.log(res);
        this.getUsers();
      });
    },
  },

  // 删除按钮

  created() {
    this.getUsers();
  },
};
</script>

<style lang="scss" scoped>
.el-table {
  margin: 0 auto;
}

.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}
.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}
.el-pagination {
  margin: 10px 0;
  justify-content: center;
}
.header {
  width: 1200px;
  margin: 10px auto;
}

.dialog-footer button:first-child {
  margin-right: 10px;
}
.username {
  cursor: pointer;
}
</style>
